#include<iostream>
#include<cstdlib>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<string>
//管道：
//Father->read
//Child->write
int main()
{
    //1.创建管道
    int fd[2] = {0};
    int pipe_d = pipe(fd);//fd输出型参数

    if(pipe_d != 0)//创建失败
    {
        std:: cerr << "pipe error" << std:: endl;
        return 1;
    }

    //2.创建子进程
    pid_t id = fork();

    if(id < 0)
    {
        std:: cerr << "fork error" << std:: endl;
        return 2;
    }
    else if(id == 0)
    {
        //子进程
        //3.关闭不需要的fd,关闭read
        ::close(fd[0]);

        int cnt = 0;
        int total = 0;
        while(true)
        {
            // std::string message = "hello vscode";
            // message += std::to_string(getpid());
            // message += ",";
            // message += std::to_string(cnt);
            // //写
            // ::write(fd[1],message.c_str(),message.size());
            // cnt++;
            // sleep(1);


            // //关闭写端
            // ::close(fd[1]);
            // break;

            //关闭读端
            std::string message = "h";
            total += ::write(fd[1], message.c_str(), message.size());
            cnt++;
            std::cout << "total: " << total << std::endl;
            sleep(2);
           
            
        }
        exit(0);
    }
    else
    {
        //父进程
        //3.关闭不需要的fd，关闭write
        ::close(fd[1]);

        char buffer[1024];
        while(true)
        {
           ssize_t n = ::read(fd[0],buffer,1024);
           if(n > 0)
           {
            buffer[n] = 0;
            std::cout << "read sucess message:" << buffer << std::endl;
           }
           else if(n ==0)
           {
            // 如果写端关闭
            // 读端读完管道内部的数据，在读取的时候，
            // 就会读取到返回值0，表示对端关闭，也表示读到文件结尾
                std::cout << "n:" << n << std::endl;
                std::cout << "child quit ??? me too" << std::endl;
                break;
           }
           //读端关闭，OS杀进程-13
           close(fd[0]);
           break;
           std::cout << std::endl;
        }


        int status = 0;
        pid_t rid = waitpid(id,&status,0);
        std::cout << "father->child sucess:" << rid << "exit code:" <<
        ((status<<8)&0xFF) << ", exit sig: " << (status & 0x7F) << std::endl;

    }
    return 0;
}
